<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form size="small" :inline="true" @submit.native.prevent>
      <el-form-item label="设备编号">
        <el-input v-model="searchForm.deviceCode" placeholder="请输入" clearable @keyup.enter.native="handleSearch" />
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input v-model="searchForm.deviceName" placeholder="请输入" clearable @keyup.enter.native="handleSearch" />
      </el-form-item>
      <el-form-item label="线别名称">
        <el-input v-model="searchForm.lineId" placeholder="请输入" clearable @keyup.enter.native="handleSearch" />
      </el-form-item>
      <el-form-item label="区分">
        <el-select v-model="searchForm.type" placeholder="请选择" filterable clearable>
          <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearch" class="button"
          plain>查询</el-button>
        <el-button type="info" icon="el-icon-refresh" size="mini" @click="handleReset" class="button"
          plain>重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 顶部功能按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" plain @click="handleAdd" v-hasPermi="['paramsMain_add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" size="mini" plain @click="handleDel()" :disabled="multiple1"
          v-hasPermi="['paramsMain_delete']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" @click="handleImport('paramsMaintenance')"
          v-hasPermi="['paramsMain_upload']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" @click="handleExport()"
          v-hasPermi="['paramsMain_Export']">导出</el-button>
      </el-col>
    </el-row>
    <!-- 表 -->
    <el-table ref="tableList" v-loading="loading" :data="tableList" border :max-height="THeight" :stripe="true"
      @selection-change="handleSelectionChange1">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" key="Index" prop="Index" width="100" />
      <el-table-column label="设备编号" align="center" prop="deviceCode" />
      <el-table-column label="设备名称" align="center" prop="deviceName" />
      <el-table-column label="线别名称" align="center" prop="lineId" />
      <el-table-column label="单元号" align="center" prop="unitNo" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="SeeMaintence(scope.row)"
            v-hasPermi="['paramsMain_detail']">维护详情</el-button>
          <el-button size="mini" type="text" @click="handleDel(scope.row)"
            v-hasPermi="['paramsMain_delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <pagination :total="total" :page.sync="Page.pageNum" :limit.sync="Page.pageSize" @pagination="getInfo()" />
    <!-- 添加1 -->
    <el-dialog title="新增" :visible.sync="Open1" width="380px" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" @close="Open1Cancel">
      <el-card>
        <el-form ref="diaLogForm1" :rules="rules1" :model="diaLogForm1" label-width="85px">
          <el-form-item label="设备编号" prop="deviceCode">
            <el-input v-model="diaLogForm1.deviceCode" size="small" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="单元号" prop="unitNo">
            <el-input v-model="diaLogForm1.unitNo" size="small" placeholder="请输入" />
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain size="mini" @click="Open1Submit">确 认</el-button>
      </div>
    </el-dialog>
    <!-- 添加2 -->
    <el-dialog v-loading="dialogLoading" :title="title2" :visible.sync="Open2" width="500px" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false" @close="Open2Cancel">
      <el-card>
        <el-form ref="diaLogForm1" :model="diaLogForm1" label-width="70px">
          <el-row>
            <el-col :span="12"><el-form-item label="设备编号" prop="deviceCode">
                <el-input v-model="diaLogForm1.deviceCode" disabled size="small" /> </el-form-item></el-col>
            <el-col :span="12"><el-form-item label="单元号" prop="unitNo">
                <el-input v-model="diaLogForm1.unitNo" disabled size="small" /> </el-form-item></el-col>
          </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" size="mini" @click="addRow" plain>新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini" @click="editRow" plain :disabled="single2">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" size="mini" @click="delRow" plain :disabled="multiple2">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain size="mini" @click="handleImport('paramsMaintenance_detail')">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain size="mini" @click="handleExport2()">导出</el-button>
          </el-col>
          <el-col :span="1.5" style="float: right; margin-top: 10px">
            <el-input v-model="SearchText" placeholder="请输入关键字搜索" size="mini" clearable
              @input="intPutSearchText"></el-input>
          </el-col>
        </el-row>
        <el-table ref="dialogData" :data="filterDialogData" border :max-height="THeight2"
          @selection-change="handleSelectionChange2" multiple>
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="项目" align="center" prop="project" />
          <el-table-column label="值" align="center" prop="value" />
        </el-table>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" plain size="mini" @click="Open2Cancel">取 消</el-button>
        <el-button type="success" plain size="mini" @click="Open2Submit">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 添加/编辑3 -->
    <el-dialog :title="title3" :visible.sync="Open3" width="500px" append-to-body :close-on-click-modal="false"
      :close-on-press-escape="false" @close="Open3Cancel">
      <el-card>
        <el-form ref="diaLogForm3" :rules="rules3" :model="diaLogForm3" label-width="65px">
          <el-form-item label="项目" prop="project">
            <el-input v-model="diaLogForm3.project" size="small" />
          </el-form-item>
          <el-form-item label="值" prop="value">
            <el-input v-model="diaLogForm3.value" size="small" />
          </el-form-item>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain size="mini" @click="Open3Submit">确 认</el-button>
      </div>
    </el-dialog>
    <!-- 文件导入 -->
    <UploadExcel ref="child" :moban="moban" :relations="relations" @child-event="ImportFile"></UploadExcel>
  </div>
</template>

<script>
  import {
    reqGetSystemSetting,
    reqInsertSystemSetting,
    reqDeleteSystemSetting,
    reqUpdateSystemSetting,
  } from "@/api/newApi/OCAP/index.js";
  import moment from "moment";
  import XLSX from "xlsx";
  export default {
    components: {
      UploadExcel: () => import("@/views/components/uploadExcel"),
    },
    data() {
      return {
        THeight: undefined,
        THeight2: undefined,
        loading: false,
        dialogLoading: false,
        tableList: [],
        selection1: [],
        // 查询参数
        searchForm: {},
        Page: { pageNum: 1, pageSize: 20 },
        total: 0,
        rules1: {
          deviceCode: {
            required: true,
            message: "设备编号必填",
            trigger: "blur",
          },
          unitNo: {
            required: true,
            message: "单元号必填",
            trigger: "blur",
          },
        },
        rules3: {
          project: {
            required: true,
            message: "项目必填",
            trigger: "blur",
          },
          value: {
            required: true,
            message: "值必填",
            trigger: "blur",
          },
        },
        Open1: false,
        Open2: false,
        Open3: false,
        title2: null,
        title3: null,
        // 表单参数
        diaLogForm1: {},
        diaLogForm3: {},
        // 非单个禁用
        single2: true,
        // 非多个禁用
        multiple1: true,
        multiple2: true,
        ids: [],
        Indexs: [],
        //处置方式
        deviceCode: null, //当前处理deviceCode
        unitNo: null, //当前处理unitNo
        dialogData: [], //表格数据
        filterDialogData: [], //过滤的表格数据
        SearchText: null,
        moban: null,
        fileList: [], //上传文件
        relations: {
          设备编号: "deviceCode",
          单元号: "unitNo",
        },
        //区分
        types: [
          {
            value: "FPC",
            label: "FPC",
          },
          {
            value: "SMT",
            label: "SMT",
          },
        ],
      };
    },
    computed: {},
    watch: {
      // 表格搜索框
      dialogData(newV, oldV) {
        this.filterDialogData = this.dialogData.filter(
          (data) =>
            !this.SearchText ||
            data.project.toLowerCase().includes(this.SearchText.toLowerCase()) ||
            data.value.toLowerCase().includes(this.SearchText.toLowerCase())
        );
      },
    },
    mounted() {
      this.THeight = (72 * window.innerHeight) / 100;
      this.THeight2 = (60 * window.innerHeight) / 100;
      this.getInfo();
    },
    methods: {
      //searchText改变
      intPutSearchText(val) {
        this.filterDialogData = this.dialogData.filter(
          (data) =>
            !val ||
            data.project.toLowerCase().includes(val.toLowerCase()) ||
            data.value.toLowerCase().includes(val.toLowerCase())
        );
      },
      //给数据加id,Index
      addIdIndex(resData) {
        this.tableList = resData.map((item, index) => {
          return {
            id: (this.Page.pageNum - 1) * this.Page.pageSize + index + 1,
            Index: (this.Page.pageNum - 1) * this.Page.pageSize + index + 1,
            ...item,
          };
        });
      },
      async getInfo() {
        //前后去空格
        if (this.searchForm.deviceCode) {
          this.searchForm.deviceCode = this.searchForm.deviceCode.trim();
        }
        this.loading = true;
        let res = await reqGetSystemSetting(
          Object.assign(this.searchForm, this.Page)
        );
        if (res.code == 0) {
          this.addIdIndex(res.data);
          this.total = res.total;
        } else {
          this.$modal.msgError(res.message);
        }
        this.loading = false;
      },
      handleSearch() {
        this.Page.pageNum = 1;
        this.getInfo();
      },
      // 重置
      handleReset() {
        this.searchForm = {};
        this.Page.pageNum = 1;
        this.getInfo();
      },
      handleAdd() {
        this.Open1 = true;
      },
      //维护详情
      SeeMaintence(row) {
        this.title2 = "维护详情";
        this.diaLogForm1 = { ...row };
        this.dialogData = JSON.parse(JSON.stringify(row.alerts));
        this.deviceCode = row.deviceCode;
        this.unitNo = row.unitNo;
        this.Open2 = true;
      },
      // 多选框选中数据
      handleSelectionChange1(selection) {
        this.selection1 = selection;
        this.ids = selection.map((item) => item.id).sort((a, b) => b - a);
        this.Indexs = selection.map((item) => item.Index).sort((a, b) => b - a);
        this.multiple1 = !selection.length; // 非多个禁用
      },
      // 多选框选中数据
      handleSelectionChange2(selection) {
        this.ids = selection.map((item) => item.id).sort((a, b) => b - a);
        this.single2 = selection.length != 1; // 非单个禁用
        this.multiple2 = !selection.length; // 非多个禁用
      },
      //添加行
      addRow() {
        //取消勾选
        for (let i = 0; i < this.ids.length; i++) {
          this.dialogData.forEach((item, index) => {
            if (item.id == this.ids[i]) {
              this.$refs.dialogData.toggleRowSelection(item, false);
            }
          });
        }
        this.title3 = "添加";
        this.diaLogForm3 = {};
        this.resetForm("diaLogForm3");
        this.Open3 = true;
        this.SearchText = null;
      },
      //编辑行
      editRow() {
        this.title3 = "修改";
        let oldDialogData = JSON.parse(JSON.stringify(this.dialogData)); //深拷贝
        oldDialogData.forEach((item) => {
          if (item.id == this.ids[0]) {
            this.diaLogForm3 = item;
          }
        });
        this.Open3 = true;
      },
      //删除行
      delRow() {
        for (let i = 0; i < this.ids.length; i++) {
          //删除行
          this.dialogData.forEach((item, index) => {
            if (item.id == this.ids[i]) {
              this.dialogData.splice(index, 1);
            }
          });
        }
        //重新排序
        this.dialogData.forEach((item, index) => {
          item.id = index;
        });
        //重新赋值
        this.dialogData = [...this.dialogData];
      },
      Open1Cancel() {
        this.resetForm("清除所有");
        this.resetForm("diaLogForm1");
      },
      Open1Submit() {
        this.$refs["diaLogForm1"].validate((valid) => {
          if (valid) {
            //请求该设备是否已添加
            let reqForm = { ...this.diaLogForm1, alerts: [] };
            this.deviceCode = this.diaLogForm1.deviceCode.trim();
            this.unitNo = this.diaLogForm1.unitNo.trim();
            reqInsertSystemSetting(reqForm).then((res) => {
              if (res.code == 0) {
                this.$modal.msgSuccess("添加成功，请维护详细信息");
                this.title2 = "详细信息";
                this.Open2 = true;
                this.getInfo();
              } else if (res.code == 1) {
                this.$modal.msgError(res.message);
              }
            });
          }
        });
      },
      //取消2
      Open2Cancel() {
        this.resetForm("清除所有");
      },
      //提交2，发请求
      async Open2Submit() {
        let reqForm = {
          unitNo: this.unitNo,
          deviceCode: this.deviceCode,
          alerts: this.dialogData,
        };
        this.dialogLoading = true;
        let res = await reqUpdateSystemSetting(reqForm);
        this.dialogLoading = false;
        if (res.code == 0) {
          this.$modal.msgSuccess("保存成功");
          this.resetForm("清除所有");
          this.getInfo();
        } else {
          this.$modal.msgError(res.msg);
        }
      },
      Open3Cancel() {
        this.Open3 = false;
      },
      //提交3，将数据保存到dialogData
      Open3Submit() {
        this.$refs["diaLogForm3"].validate((valid) => {
          if (valid) {
            if (this.title3 == "添加") {
              this.dialogData.push({
                id: this.dialogData.length,
                project: this.diaLogForm3.project,
                value: this.diaLogForm3.value,
              });
            } else if (this.title3 == "修改") {
              this.dialogData.forEach((item) => {
                if (item.id == this.ids[0]) {
                  item.project = this.diaLogForm3.project;
                  item.value = this.diaLogForm3.value;
                }
              });
            }
            this.Open3 = false;
          }
        });
      },
      //删除
      handleDel(row) {
        let delArr = [];
        let Indexs = [];
        if (row) {
          delArr = [{ unitNo: row.unitNo, deviceCode: row.deviceCode }];
          Indexs = row.Index;
        } else {
          for (let i = 0; i < this.selection1.length; i++) {
            delArr.push({
              unitNo: this.selection1[i].unitNo,
              deviceCode: this.selection1[i].deviceCode,
            });
          }
          Indexs = this.Indexs.sort((a, b) => a - b);
        }
        this.$modal
          .confirm('是否确认删除序号为"' + Indexs + '"的数据项？')
          .then(() => {
            return reqDeleteSystemSetting(delArr);
          })
          .then((res) => {
            if (res.code == 0) {
              this.$modal.msgSuccess("删除成功");
              //最后一页只剩1条数据，删除后pageNum--
              if (this.tableList.length == 1 && this.Page.pageNum > 1) {
                this.Page.pageNum--;
              }
              this.getInfo();
            }
          })
          .catch(() => { });
      },
      resetForm(name) {
        if (name == "清除所有") {
          this.Open1 = false;
          this.Open2 = false;
          this.diaLogForm1 = {};
          this.diaLogForm3 = {};
          this.dialogData = [];
          this.SearchText = null;
        }
      },
      //导入
      handleImport(name) {
        this.moban = name;
        if (name == "paramsMaintenance_detail") {
          this.relations = {
            项目: "project",
            值: "value",
          };
        }
        this.$refs.child.dialogOpen();
      },
      ImportFile(reqArr, fileItem) {
        if (this.moban == "paramsMaintenance") {
          //将reqArr数组中每个对象的属性的属性值都改为字符串类型
          for (let i = 0; i < reqArr.length; i++) {
            for (let key in reqArr[i]) {
              if (reqArr[i][key] !== null) {
                reqArr[i][key] = reqArr[i][key].toString();
              }
            }
          }
          reqArr.forEach((item) => {
            item.alerts = [];
          });
          Promise.all(reqArr.map((req) => reqInsertSystemSetting(req)))
            .then((responses) => {
              const success = responses.every((response) => response.code === 0);
              const has0 = responses.some((response) => response.code === 0);
              if (success) {
                this.$modal.msgSuccess("导入成功");
                this.$refs.child.uploadCancel();
                this.getInfo();
              } else {
                //将失败的数据的索引存入数组
                let indexArr1 = [];
                let indexArr2 = [];
                responses.forEach((item, index) => {
                  if (
                    item.code != 0 &&
                    item.message == "该设备已添加，请勿重复添加"
                  ) {
                    indexArr1.push(index + 2);
                  }
                  if (item.code != 0 && item.message == "设备编号未维护") {
                    indexArr2.push(index + 2);
                  }
                });
                let Msg = "";
                if (indexArr1.length > 0) {
                  Msg = `第${indexArr1.toString()}行设备已添加，请勿重复添加;`;
                }
                if (indexArr2.length > 0) {
                  Msg += `第${indexArr2.toString()}行设备编号未维护，无法添加;`;
                }
                if (has0) {
                  Msg += "(其他行已成功添加)";
                }
                let spanText = Msg.split(";").map(
                  (item) => `<span style='margin:10px;'>${item}</span><br/>`
                );
                this.$message({
                  dangerouslyUseHTMLString: true,
                  message: `<div style='overflow: auto;max-height: 70vh'>
          ${spanText.join("")}
            </div>`,
                  type: "error",
                });
                this.getInfo();
              }
            })
            .catch((error) => {
              this.$modal.msgError("导入失败: " + error.message);
            });
        } else if ((this.moban = "paramsMaintenance_detail")) {
          //如果this.dialogData中无reqArr中的数据，则将数据存入this.dialogData中
          // reqArr.forEach((item) => {
          //   if (
          //     !this.dialogData.some(
          //       (i) => i.project === item.project && i.value === item.value
          //     )
          //   ) {
          //     let newItem = {
          //       id: this.dialogData.length + 1,
          //       ...item,
          //     };
          //     this.dialogData.push(newItem);
          //     this.$refs.child.uploadCancel();
          //   }
          // });
          reqArr.forEach((item) => {
            let newItem = {
              id: this.dialogData.length + 1,
              // ...item,
              project: item.project.toString(),
              value: item.value.toString(),

            };
            this.dialogData.push(newItem);
            this.$refs.child.uploadCancel();
          });
        }
      },
      //导出
      async handleExport() {
        if (this.tableList.length > 0) {
          const loading = this.$loading({
            lock: true,
            text: `Loading`,
            spinner: "el-icon-loading",
          });
          try {
            const headers = [
              "设备编号",
              "设备名称",
              "线别名称",
              "单元号",
              "维护详情",
            ];
            //前后去空格
            if (this.searchForm.deviceCode) {
              this.searchForm.deviceCode = this.searchForm.deviceCode.trim();
            }
            let Page = { pageSize: this.total, pageNum: 1 };
            let res = await reqGetSystemSetting(
              Object.assign(this.searchForm, Page)
            );
            const datas = res.data.map((item) => [
              item.deviceCode,
              item.deviceName,
              item.lineId,
              item.unitNo,
              JSON.stringify(item.alerts),
            ]);
            const worksheet = XLSX.utils.aoa_to_sheet([headers, ...datas]);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");
            XLSX.writeFile(
              workbook,
              `参数维护${moment(new Date()).format("yyyy-MM-DD HH:mm")}.xlsx`
            );
          } catch (error) {
            console.error("导出数据失败:", error);
          } finally {
            loading.close();
          }
        } else {
          this.$modal.msgError("暂无数据可导出");
        }
      },
      //导出
      async handleExport2() {
        if (this.dialogData.length > 0) {
          const loading = this.$loading({
            lock: true,
            text: `Loading`,
            spinner: "el-icon-loading",
          });
          try {
            const headers = ["项目", "值"];
            const datas = this.dialogData.map((item) => [
              item.project,
              item.value,
            ]);
            const worksheet = XLSX.utils.aoa_to_sheet([headers, ...datas]);
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");
            XLSX.writeFile(workbook, `${this.deviceCode}-维护详情.xlsx`);
          } catch (error) {
            console.error("导出数据失败:", error);
          } finally {
            loading.close();
          }
        } else {
          this.$modal.msgError("暂无数据可导出");
        }
      },
    },
  };
</script>

<style lang="scss" scoped>
  .service {
    padding: 0 20px;
  }

  ::v-deep .el-input--small .el-input__inner {
    height: 30px !important;
    line-height: 30px !important;
  }

  ::v-deep .el-table .el-table__header-wrapper th,
  .el-table .el-table__fixed-header-wrapper th {
    background-color: #f0f8ff !important;
  }

  ::v-deep .el-dialog__body {
    padding: 5px 20px !important;
  }

  ::v-deep .el-input.is-disabled .el-input__inner {
    color: #515a6e !important;
  }

  ::v-deep .box-card .el-form-item {
    margin-bottom: 2px !important;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>